// 修改PropertiesUtils.java
package com.xyh.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Properties;

public class PropertiesUtils {
    private static final Logger logger = LoggerFactory.getLogger(PropertiesUtils.class);
    private static Properties properties = new Properties();

    static {
        try {
            // 首先尝试加载外部配置文件
            File externalFile = new File("./application.properties");
            if (externalFile.exists() && externalFile.canRead()) {
                logger.info("正在加载外部配置文件: {}", externalFile.getAbsolutePath());
                try (FileInputStream fis = new FileInputStream(externalFile);
                     InputStreamReader reader = new InputStreamReader(fis, StandardCharsets.UTF_8)) {
                    properties.load(reader);
                    logger.info("成功加载外部配置文件");
                }
            } else {
                // 如果外部文件不存在或无法读取，加载类路径中的配置
                logger.info("外部配置文件不存在或无法读取，使用内部配置");
                try (InputStreamReader reader = new InputStreamReader(
                        PropertiesUtils.class.getClassLoader().getResourceAsStream("application.properties"),
                        StandardCharsets.UTF_8)) {
                    properties.load(reader);
                    logger.info("成功加载内部配置文件");
                }
            }
        } catch (Exception e) {
            logger.error("加载配置文件出错", e);
            throw new RuntimeException("加载配置文件出错", e);
        }
    }

    public static String getProperty(String key) {
        return properties.getProperty(key);
    }

    public static String getProperty(String key, String defaultValue) {
        return properties.getProperty(key, defaultValue);
    }
}